package com.example.zbh.dsliao.ui.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMConnectionListener;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMConversation;
import com.easemob.exceptions.EaseMobException;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.db.DatabaseHelper;
import com.example.zbh.dsliao.db.entity.UserContact;
import com.example.zbh.dsliao.model.entity.ContactPeople;
import com.example.zbh.dsliao.presenter.ContactListPresenter;
import com.example.zbh.dsliao.ui.activty.AddContactActivity;
import com.example.zbh.dsliao.ui.activty.CharActivity;
import com.example.zbh.dsliao.ui.activty.ChatRoomActivity;
import com.example.zbh.dsliao.ui.activty.GroupsActivity;
import com.example.zbh.dsliao.ui.activty.NewFriendsMsgActivity;
import com.example.zbh.dsliao.ui.adapter.ContactAdapter;
import com.example.zbh.dsliao.ui.viewinterface.ViewContactInterface;
import com.example.zbh.dsliao.utils.DliaoUtils;
import com.example.zbh.dsliao.view.CustomChangeDialog;
import com.example.zbh.dsliao.view.CustomDialog;
import com.example.zbh.dsliao.view.FancyIndexer;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import de.greenrobot.event.EventBus;



/**
 * 通讯录页面fragment
 */
public class ContactListFragment extends MVPBaseFragment<ViewContactInterface, ContactListPresenter> implements ViewContactInterface, FancyIndexer.OnTouchLetterChangedListener, View.OnClickListener, ContactAdapter.OnlongClickItemLisener, TextWatcher{
    private ContactAdapter contactAdapter;
    private ListView listView;
    private FancyIndexer mFancyIndexer;
    private Button add_contact;
    private TextView apply_notice, group_talk, talk_room;//申请与应用, 群聊,聊天室
    private List<ContactPeople> list;
    private ImageView contactlist_msg_number;
    private CustomDialog customDialog;
    private PopupWindow window;
    private EditText queryConversation;
    private ImageView queryDeleteBtn;
    private String username;
    private LinearLayout back;

    private Handler handler;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            createPresenter().startGetContact();
        }
    };


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }


    /**
     * 监听主界面的eventbus发过来的的状态
     * (包括 1 == 账号被服务器删除
     * 2 == 账号被别的设备登录)
     **/
    public void onEventMainThread(Integer data) {
        if (data == 102) {
            DliaoUtils.showDialogConnection(getActivity());
        } else if (data == 101) {
            DliaoUtils.showDialogUserRemoved(getActivity());
        }
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contactlist, container, false);
        listView = (ListView) view.findViewById(R.id.lv_content);
        mFancyIndexer = (FancyIndexer) view.findViewById(R.id.bar);
        add_contact = (Button) view.findViewById(R.id.add_contact);
        queryConversation = (EditText) view.findViewById(R.id.queryConversation);
        queryDeleteBtn = (ImageView) view.findViewById(R.id.queryDeleteBtn);
        back = (LinearLayout) view.findViewById(R.id.back);
        return view;
    }

    @Override
    protected void initData() {
        handler = new Handler();
        back.setVisibility(View.GONE);
        View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.dl_contacts_header, null);
        apply_notice = (TextView) headerView.findViewById(R.id.apply_notice);
        group_talk = (TextView) headerView.findViewById(R.id.group_talk);
        talk_room = (TextView) headerView.findViewById(R.id.talk_room);
        contactlist_msg_number = (ImageView) headerView.findViewById(R.id.contactlist_msg_number);
        apply_notice.setOnClickListener(this);
        group_talk.setOnClickListener(this);
        talk_room.setOnClickListener(this);
        listView.addHeaderView(headerView);
        contactAdapter = new ContactAdapter(getActivity());
        listView.setAdapter(contactAdapter);
        mFancyIndexer.setOnTouchLetterChangedListener(this);
        createPresenter().startGetContact();
        add_contact.setOnClickListener(this);
        Log.i("nanchaodong", ">>>>>>>>>>>>>>>>>>>>>>>");
        contactAdapter.setOnlongClickItemLisener(this);
        queryConversation.addTextChangedListener(this);
        queryDeleteBtn.setOnClickListener(this);


    }

    /**
     * edittext监听
     **/
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        if (s.length() > 0) {
            queryDeleteBtn.setVisibility(View.VISIBLE);
        } else {
            queryDeleteBtn.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        contactAdapter.getFilter().filter(s);
        if (s.length() == 0) {
            queryDeleteBtn.setVisibility(View.INVISIBLE);
            handler.postDelayed(runnable, 200);
        }
    }



    /**
     * 初始化指挥家
     **/
    @Override
    protected ContactListPresenter createPresenter() {
        Log.i("nan", 1 + "");
        return new ContactListPresenter(this);
    }


    //字母改变监听
    @Override
    public void onTouchLetterChanged(String s) {
        for (int i = 1; i <= list.size(); i++) {
            Log.i("nan", 6 + "" + s);
            ContactPeople people = list.get(i - 1);
            String letter = people.getPinyin().charAt(0) + "";
            Log.i("nannannan", letter);
            if (letter.equals(letter.toLowerCase())) {
                letter = letter.toUpperCase();
                Log.i("nannannan", letter);
            }
            if (TextUtils.equals(letter, s)) {
                Log.i("nan", letter + "----" + s + i);
                listView.setSelection(i);
                break;
            }
        }
    }

    @Override
    public void showContactList(List<ContactPeople> list) {
        Log.i("nan", 5 + "");
        this.list = list;
        Log.i("sssssss", list.toString());
        Log.i("ssssssssssss", list.size() + "sssss>>>>>>>>");

        contactAdapter.addData(list);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_contact:
                Intent intent = new Intent();
                intent.setClass(getActivity(), AddContactActivity.class);
                startActivity(intent);
                break;
            case R.id.apply_notice:
                Intent newF = new Intent();
                newF.setClass(getActivity(), NewFriendsMsgActivity.class);
                startActivity(newF);
                break;
            case R.id.group_talk:
                Intent newG = new Intent();
                newG.setClass(getActivity(), GroupsActivity.class);
                startActivity(newG);
                break;
            case R.id.talk_room:
                Intent intentRoom = new Intent();
                intentRoom.setClass(getActivity(), ChatRoomActivity.class);
                startActivity(intentRoom);
                break;
            case R.id.queryDeleteBtn://搜索框的删除按钮
                queryConversation.getText().clear();
                hideSoftKeyboard();//隐藏键盘
                queryDeleteBtn.setVisibility(View.INVISIBLE);
                break;
        }

    }

    /**
     * 删除联系人
     **/
    private void deleteContact() {
        customDialog = new CustomDialog(getActivity(), "玩命删除中..稍等..");
        customDialog.show();
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMContactManager.getInstance().deleteContact(username);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            refreshUser();
                            customDialog.dismiss();
                            Log.i("dada", "删除成功0>>>>>>>>>");
                        }
                    });
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    /**
     * 将联系人加入黑名单
     **/
    private void inBlack() {
        customDialog = new CustomDialog(getActivity(), "正在移入黑名单...");
        customDialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMContactManager.getInstance().addUserToBlackList(username, false);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "已将" + username + "加入黑名单", Toast.LENGTH_SHORT).show();
                            //刷新
                            refreshUser();
                            customDialog.dismiss();
                        }
                    });
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * 加入黑名单之后 刷新联系人列表
     **/
    private void refreshUser() {
        handler.post(runnable);
    }


    /**
     * listview点击事件(长按, 短按)
     **/
    @Override
    public void onlongClickItem(View view, int code, int position) {
        Intent intent = new Intent();
        username = (String) contactAdapter.getItem(position);
        //如果username 是昵称 遍历数据库
        UserContact userContact = DatabaseHelper.getInstance().queryContactPeopleBynickName(username);
        if (userContact != null) {
            username = userContact.getUsername();
        }
        intent.putExtra("userName", username);
        //正常点击
        if (code == 1) {
            Log.i("taggggg", (String) contactAdapter.getItem(position));
            intent.setClass(getActivity(), CharActivity.class);
            startActivity(intent);
            Log.i("taggggg", position + "");
        }
        //长按点击
        else if (code == 2) {
            showDialog();//弹出dialog
        }
    }

    /**
     * 长按联系人行布局弹出dialog
     **/
    private void showDialog() {
        //弹出提示dialog
        final CustomChangeDialog customChangeDialog = new CustomChangeDialog(getActivity(), "请选择..", View.VISIBLE, "删除联系人", "加入黑名单", "取消");
        customChangeDialog.show();
        customChangeDialog.setCustomChangeDialogListener(new CustomChangeDialog.CustomChangeDialogListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.changeOneBtn://点击删除按钮
                        customChangeDialog.dismiss();
                        deleteContact();//删除联系人方法
                        break;
                    case R.id.changeTwoBtn://点击加入黑名单按钮
                        customChangeDialog.dismiss();
                        inBlack();//加入黑名单方法
                        break;
                    case R.id.cancleBtn://取消按钮
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse("tel:13664266902"));
                        startActivity(intent);
                        customChangeDialog.dismiss();
                        break;

                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        handler.post(runnable);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
